package com.mybatis_db_read_writer.config;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 数据库上下文切换
 * @author nie_chaoqun
 * @date
 */
public class DbContextHolder {
    private static final ThreadLocal<DbTypeEnum> dbContextHolder=new ThreadLocal<>();
    private static final AtomicInteger counter=new AtomicInteger();

    public static void set(DbTypeEnum dbTypeEnum){
        dbContextHolder.set(dbTypeEnum);
    }
    public static DbTypeEnum get(){
        return dbContextHolder.get();
    }
    public static void master(){
        set(DbTypeEnum.MASTER);
        System.out.println("切换到master");
    }
    public static void slave(){
        //轮询
        int index=counter.getAndIncrement()%2;
        if(counter.get()>9999){
            counter.set(-1);
        }
        if(index==0){
            set(DbTypeEnum.SLAVE1);
            System.out.println("切换到slave1");
        }else{
            set(DbTypeEnum.SLAVE2);
            System.out.println("切换到slave2");
        }
    }
}
